<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>
    <title>title</title>
    <link rel="stylesheet" type="text/css" href="../css/api.css"/>
    <style>
        html, body {
            background-color: #f8f8f8;
        }
        .main ul li {
            margin-bottom: 6px;
        }
        .li_box {
            background-color: #fff;
            padding: 15px 15px 6px;
        }
        .li_box .li_boxt {
            display: -webkit-box;
            display: -webkit-flex;
            align-items: center;
            margin-bottom: 12px;
        }
        .li_box .li_boxt .info_box {
            padding-right: 5px;
            flex: 1;
            -webkit-flex: 1;
            box-flex: 1;
            -webkit-box-flex: 1;
        }
        .li_box .li_boxt .info_box .title {
            color: #333;
            font-size: 16px;
            margin-bottom: 9px;
        }
        .li_box .li_boxt .info_box .info {
            color: #999;
            font-size: 12px;
        }
        .li_box .li_boxt .btn_box .btn {
            width: 65px;
            height: 24px;
            line-height: 24px;
            text-align: center;
            border-radius: 5px;
            background-color: #e62442;
            color: #fff;
            font-size: 12px;
        }
        .li_box .li_boxt .btn_box .btn.active {
            background-color: #1ad469;
        }
        .li_box .li_boxb .address_box {
            display: -webkit-box;
            display: -webkit-flex;
            padding-bottom: 5px;
        }
        .li_box .li_boxb .address_box .address_boxl {
            padding-right: 5px;
        }
        .li_box .li_boxb .address_box .address_boxl img {
            width: 18px;
            display: block;
        }
        .li_box .li_boxb .address_box .address_boxr {
            width: 0;
            flex: 1;
            -webkit-flex: 1;
            box-flex: 1;
            -webkit-box-flex: 1;
        }
        .li_box .li_boxb .address_box .address_boxr .address {
            font-size: 13px;
            color: #333;
        }
    </style>
</head>
<body>
    <div class="main">
        <ul id="orderC">
            <!-- <li>
                <div class="li_box">
                    <div class="li_boxt">
                        <div class="info_box">
                            <div class="title">商家名称</div>
                            <div class="info">距离0.43km | 配送费 6</div>
                        </div>
                        <div class="btn_box">
                            <div class="btn" tapmode onclick="grabOrderNow();">立即抢单</div>
                        </div>
                    </div>
                    <div class="li_boxb">
                        <div class="address_box">
                            <div class="address_boxl">
                                <img src="../image/merchant_address.png">
                            </div>
                            <div class="address_boxr">
                                <div class="address">商家地址</div>
                            </div>
                        </div>
                        <div class="address_box">
                            <div class="address_boxl">
                                <img src="../image/client_address.png">
                            </div>
                            <div class="address_boxr">
                                <div class="address">客户地址</div>
                            </div>
                        </div>
                    </div>
                </div>
            </li>
            <li>
                <div class="li_box">
                    <div class="li_boxt">
                        <div class="info_box">
                            <div class="title">商家名称</div>
                            <div class="info">距离0.43km | 配送费 6</div>
                        </div>
                        <div class="btn_box">
                            <div class="btn active">抢单成功</div>
                        </div>
                    </div>
                    <div class="li_boxb">
                        <div class="address_box">
                            <div class="address_boxl">
                                <img src="../image/merchant_address.png">
                            </div>
                            <div class="address_boxr">
                                <div class="address">商家地址</div>
                            </div>
                        </div>
                        <div class="address_box">
                            <div class="address_boxl">
                                <img src="../image/client_address.png">
                            </div>
                            <div class="address_boxr">
                                <div class="address">客户地址</div>
                            </div>
                        </div>
                    </div>
                </div>
            </li> -->
        </ul>
    </div>
</body>
<script type="text/javascript" src="../script/api.js"></script>
<script type="text/javascript" src="../script/doT.min.js"></script>
<script type="text/javascript" src="../script/zepto.js"></script>
<script type="text/javascript" src="../script/common.js"></script>
<script id="orderL" type="text/x-dot-template">
    {{ for (var i = 0; i < it.length; i++) { }}
        <li id="oid_{{=it[i]['id']}}" tapmode onclick="fnToOrderDetail('{{=it[i]["id"]}}','{{=it[i]["type"]}}');">
            <div class="li_box">
                <div class="li_boxt">
                    <div class="info_box">
                        <div class="title">{{=it[i]['name']}}</div>
                        <div class="info">距离{{=formatDistance(it[i]['distance'])}}km | 配送费RM {{=it[i]['delivery_price']}}</div>
                    </div>
                    <div class="btn_box">
                        {{if(it[i]['staff_id'] > 0){ }}
                            <div class="btn active">抢单成功</div>
                        {{ } else{ }}
                            <div class="btn" tapmode onclick="grabOrderNow({{=it[i]['id']}},this);">立即抢单</div>
                        {{ }; }}
                    </div>
                </div>
                <div class="li_boxb">
                    <div class="address_box">
                        <div class="address_boxl">
                            <img src="../image/merchant_address.png">
                        </div>
                        <div class="address_boxr">
                            <div class="address">{{=it[i]['address']}}</div>
                        </div>
                    </div>
                    <div class="address_box">
                        <div class="address_boxl">
                            <img src="../image/client_address.png">
                        </div>
                        <div class="address_boxr">
                            <div class="address">{{=it[i]['area_name2']}}{{=it[i]['address_detail']}}</div>
                        </div>
                    </div>
                </div>
            </div>
        </li>
    {{ }; }}
</script>
<script type="text/javascript">
    var p = 1; // 默认第一页
    var canLoad = false; // 默认不可上拉加载更多
    var tempTimer; // 定义默认定时器
    var tempSecond = 0; // 定义默认轮询的秒数 
    var locationSuccess = false; // 默认定位失败

    apiready = function(){
        openLoading();
        staffData = $api.getStorage('staff_data');
        // getOrderList();
        // 下拉刷新
        api.setCustomRefreshHeaderInfo({
            bgColor: '#f8f8f8',
            loadAnimInterval:60,
            image: {
               pull: pullArr,
               load: loadArr
            }
        }, function(ret, err) {
            tempSecond = 0;
            locationSuccess =false;
            // 先去获取定位位置，如果有返回，则去获取订单，否则提示定位失败
            var GoogleMap = api.require('googleMap');
            GoogleMap.getLocation(function(ret) {
                if (ret.status) {
                    $api.setStorage('staff_lng',ret.lon);
                    $api.setStorage('staff_lat',ret.lat);
                    api.ajax({
                        url: rootPath + '/api/staff/update_log_lat',
                        method: 'post',
                        data: {
                            values: { 
                                staff_id: staffData.id,
                                staff_token: staffData.token,
                                lng: ret.lon,
                                lat: ret.lat
                            },
                        }
                    }, function(ret2, err2) {
                        if( ret2 && ret2.status == 200){
                            locationSuccess = true;
                            p = 1;
                            canLoad = false;
                            getOrderList(1);
                            clearInterval(tempTimer);
                        }else{
                            locationSuccess = false;
                        }
                    });
                }else{
                    locationSuccess = false;
                }
            });
            // 因为getlocation没有回调返回，所以增加5秒判断是否定位成功
            tempTimer = setInterval(function(){
                if(locationSuccess == true){
                    // 如果定位成功，则关闭定时器，走下面的流程
                    clearInterval(tempTimer);
                }else{
                    // 定位失败，记录失败次数
                    tempSecond++
                }
                if(tempSecond >= 10){
                    // 失败次数大于5秒（10次），则表示定位失败，提示定位失败逻辑
                    clearInterval(tempTimer);
                    api.refreshHeaderLoadDone();
                    evDoWithoutLngAndLat();
                }
            },500)
            /*p = 1;
            canLoad = false;
            getOrderList(1);*/
        });

        // 上拉加载
        api.addEventListener({
            name:'scrolltobottom',
            extra:{
                threshold:0            //设置距离底部多少距离时触发，默认值为0，数字类型
            }
        }, function(ret, err){
            if(canLoad == true){
                canLoad = false;
                var _dom = $api.byId('orderC');
                setLoadingData(_dom);
                getOrderList(2);
            }
        });

        /*api.addEventListener({
            name: 'loginSuccess'
        }, function(ret, err){
            if( ret ){
                staffData = $api.getStorage('staff_data');
                p = 1;
                canLoad = false;
                getOrderList(1);
            }
        });*/

        // 指派订单
        api.addEventListener({
            name: 'appointOrder'
        }, function(ret, err){
            if( ret ){
                var staffId = ret.value.staffId;
                var orderId = ret.value.orderId;
                var userAddress = ret.value.userAddress;
                var shopAddress = ret.value.shopAddress;
                var shopDistance = ret.value.shopDistance;
                var rejectTime = ret.value.rejectTime;
                var deliveryPrice = ret.value.deliveryPrice;
                fnSocketOrderDialog(staffId,orderId,userAddress,shopAddress,shopDistance,rejectTime,deliveryPrice);
            }
        });

        api.addEventListener({
            name: 'appointSuccess'
        }, function(ret, err){
            if( ret ){
                $("#oid_"+ret.value.orderId).find('.btn_box .btn').html('接单成功');
                $("#oid_"+ret.value.orderId).find('.btn_box .btn').addClass('active');
            }
        });

        // 继续查询其他指派的订单
        api.addEventListener({
            name: 'checkNextAppoint'
        }, function(ret, err){
            if( ret ){
                // 无论是成功接单，还是拒绝后，还是接单没返回，只有操作过就要再查询是否有其他指派，直至查完为止
                checkAppointOrder();
            }
        });

        // 如果用户同意获取地理位置，则刷新页面
        api.addEventListener({
            name: 'refreshGetOrderFrame'
        }, function(ret, err){
            if( ret ){
                p = 1;
                canLoad = false;
                getOrderList();
            }
        });

        // 查看是否有指派的订单未处理的
        checkAppointOrder();

        api.addEventListener({
            name: 'pushNewOrder'
        }, function(ret, err){
            if( ret ){
                toast('您有新的订单');
                p = 1;
                canLoad = false;
                getOrderList();
                /*var shop = ret.value.shop;
                var listT = $api.byId('orderL');
                var listTFn = doT.template(listT.text);
                var html = listTFn(shop);
                var list = $api.byId('orderC');
                $api.prepend(list,html);
                api.parseTapmode();*/
            }
        });
    };

    function fnToOrderDetail (_id,_type) {
        api.openWin({
            name: 'order_detail',
            url: './order_detail.html',
            pageParam: {
                id: _id,
                isPackage: _type
            }
        });
        event.stopPropagation();
        event.preventDefault();
        return;
    };

    function evDoWithoutLngAndLat () {
        // 获取不到地理位置信息
        var _dom = $api.byId('orderC');
        setWithoutData(_dom,'定位失败，请开启定位后刷新尝试');
        canLoad = false;
        closeLoading();
    };

    function getOrderList(t) {
        var staffLng = $api.getStorage('staff_lng');
        var staffLat = $api.getStorage('staff_lat');
        var url = rootPath + '/api/staff/get_order_list/staff_id/'+staffData.id+'/staff_token/'+staffData.token+'/p/'+p+'/lng/'+staffLng+'/lat/'+staffLat;
        api.ajax({
            url: rootPath + '/api/staff/get_order_list',
            method: 'get',
            // cache: true,
            data: {
                values: { 
                    staff_id: staffData.id,
                    staff_token: staffData.token,
                    p: p,
                    lng:staffLng,
                    lat:staffLat,
                    url:url
                },
                
            }
        }, function(ret, err) {
            if (ret.status == 200) {
                if(t == 2){
                    hideLoadingData();
                    appendDotData (ret.data,'orderL','orderC',true);
                }else{
                    setDotData (ret.data,'orderL','orderC',true);
                }
                if(ret.data.length == 10){
                    p++;
                    canLoad = true;
                }else{
                    canLoad = false;
                }
            } else {
                if(p == 1){
                    // 首次获取就无订单
                    var _dom = $api.byId('orderC');
                    setWithoutData(_dom);
                    canLoad = false;
                }
            }
            if(t == 1){
                api.refreshHeaderLoadDone();
            }
            closeLoading();
        });
    }

    // 抢单 
    function grabOrderNow (_id,_this) {
        var staffData = $api.getStorage('staff_data');
        if(staffData.is_online != 1){
            toast('请先开启接单开关');
            return;
        }
        var _that = $(_this);
        if(_that.hasClass('active')){
            return;
        }
        openLoading();
        api.ajax({
            url: rootPath + '/api/staff/grab_order_now',
            method: 'post',
            data: {
                values: { 
                    staff_id: staffData.id,
                    staff_token: staffData.token,
                    id: _id
                },
            }
        }, function(ret, err) {
            if (ret.status == 200) {
                _that.addClass('active');
                _that.html('抢单成功');
                api.toast({
                    msg: '抢单成功',
                    location: 'middle'
                });
                api.sendEvent({
                    // 因为同appointSuccess指派订单成功后需要send的event一样，所以合并为一个
                    // name: 'refreshWaitPickupOrder',
                    name: 'appointSuccess',
                });
                closeLoading();
            }else if(ret.status == 205){
                api.toast({
                    msg: ret.msg,
                    location: 'middle'
                });
                _that.parents('li').remove();
                closeLoading();
            } else {
                closeLoading();
            }
        });
        event.stopPropagation();
        event.preventDefault();
        return;
    };

    function checkAppointOrder () {
        api.ajax({
            url: rootPath + '/api/staff/check_appoint_order',
            method: 'post',
            data: {
                values: {
                    staff_id: staffData.id,
                    staff_token: staffData.token,
                },
            }
        }, function(ret, err) {
            if (ret) {
                if(ret.status == 200){
                    fnSocketOrderDialog(staffData.id,ret.data.oid,ret.data.area_name2+ret.data.address_detail,ret.data.shop_address,ret.data.shop_distance,ret.data.reject_time,ret.data.delivery_price)
                }
            }
        });
    }

    // socket推送订单弹窗
    function fnSocketOrderDialog(staffId,orderId,userAddress,shopAddress,shopDistance,rejectTime,deliveryPrice) {
        api.openFrame({
            name: 'get_order_dialog',
            url: 'get_order_dialog.html',
            rect: {
                x: 0,
                y: 0,
                w: 'auto',
                h: 'auto'
            },
            bounces: false,
            pageParam:{
                staffId: staffId, 
                orderId: orderId,
                userAddress: userAddress,
                shopAddress: shopAddress,
                shopDistance: shopDistance,
                rejectTime: rejectTime,
                deliveryPrice: deliveryPrice,
            }
        });
    }
</script>
</html>